/**
 * Copyright (c) 2018, wuxie All rights reserved.
 * qq:16349023,mail:16349023@qq.com
 * 未经许可禁止任何人通过任何渠道使用、修改源代码.
 * 项目名称 : wxcloud
 *
 * @version V1.0
 */
package cn.xo68.boot.auth.core.web;

import cn.xo68.boot.web.web.WebContext;
import cn.xo68.core.entity.JsonResponsEntity;
import cn.xo68.core.util.JsonUtil;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *  ExceptionControllerAdvice
 * @author wuxie
 * @date 2018/8/15 20:28
 *
 */
public class ExceptionControllerAdvice {

    @Autowired
    private WebContext webContext;
    @Autowired
    private JsonUtil jsonUtil;

    protected ResponseEntity<?> returnFailJson(String error){
        JsonResponsEntity<Object> jsonResponseEntity = JsonResponsEntity.fail()
                .setError(error)
                .build();
        MediaType mediaType=MediaType.APPLICATION_JSON_UTF8;
        HttpHeaders headers =webContext.buildHeaders(false, null);
        return ResponseEntity
                .status(HttpServletResponse.SC_OK)
                .cacheControl(CacheControl.noCache())
                .headers(headers)
                .contentType(mediaType)
                .body(jsonUtil.toString(jsonResponseEntity));
    }

    @ExceptionHandler({AuthorizationException.class})
    public Object unauthenticatedExceptionHandle(HttpServletRequest request,AuthorizationException e){
        return exceptionHandle(request,e);
    }

    @ExceptionHandler(Exception.class)
    public Object exceptionHandle(HttpServletRequest request,Exception e){
        boolean isResponseJson=webContext.isResponseJson(request);
        if(isResponseJson){
            return returnFailJson(e.getMessage());
        }else {
            ModelAndView mv=new ModelAndView();
            mv.addObject("error",e.getMessage());
            mv.setViewName("error/index");
            return mv;
        }
    }

}
